import { BasicRawLayout, PageRawView, BlankRawLayout } from '@/layouts';
import { h, markRaw } from 'vue';
import { v4 as uuidv4 } from 'uuid';
import api from '@/api';
import store from '@/store';
import { isMobile } from '@/utils/util';

//404
const notFoundRouter = {
    path: '/:catchAll(.*)',
    name: uuidv4(),
    redirect: '/404',
    meta: { title: '404', isHide: true }
};
let permissions = []; // 存储所有按钮权限
/**
 * 获取路由菜单信息
 *
 * 1. 调用 getRouterByUser() 访问后端接口获得路由结构数组
 *    @see https://github.com/sendya/ant-design-pro-vue/blob/feature/dynamic-menu/public/dynamic-menu.json
 * 2. 调用
 * @returns {Promise<any>}
 */
export const generatorDynamicRouter = async () => {
    const { success, moule } = await api.uacControlModel.getMenusByEmpId();
    if (success) {
        const allRouters = [];
        // 首页根路由
        const rootRouter = {
            // 路由地址 动态拼接生成如 /dashboard/workplace
            path: '/',
            redirect: '/workbench',
            // redirect: res[0].children[0].path,
            // 路由名称，建议唯一
            name: uuidv4(),
            // 该路由对应页面的 组件
            component: isMobile() ? BlankRawLayout : BasicRawLayout,
            // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
            meta: { title: 'workbench' },
            children: []
        };
        allRouters.push(rootRouter);
        console.log('routes', JSON.parse(moule));
        rootRouter.children = generator(JSON.parse(moule));
        // 添加404页面
        allRouters.push(notFoundRouter);
        // 添加所有权限
        store.commit('user/SET_AUTH', permissions);
        return allRouters;
    }
};
// 重新修改路由名称
export function createCustomComponent(name, component) {
    return new Promise((res) => {
        res({
            name,
            data() {
                return { component: null };
            },
            async created() {
                if (component instanceof Promise) {
                    try {
                        const module = await component;
                        this.component = markRaw(module?.default);
                    } catch (error) {
                        console.error(`can not resolve component ${name}, error:`, error);
                    }
                    return;
                }
                this.component = component;
            },
            render() {
                return this.component ? h(this.component) : null;
            }
        });
    });
}

const modules = import.meta.glob('@/views/**/*.vue');

/**
 * 格式化 后端 结构信息并递归生成层级路由表
 *
 * @param routerMap
 * @param parent
 * @returns {*}
 */
export const generator = (routerMap) => {
    return routerMap.map((item) => {
        const hasChildren = item.subNodes && item.subNodes.length > 0;
        let component = {};
        if (hasChildren) {
            component = isMobile() ? BlankRawLayout : PageRawView;
        } else if (item.node.menuCode) {
            const componentPath = `/src/views/${item.node.menuCode}`;
            if (modules[componentPath]) {
                component = () => createCustomComponent(
                    item.node.menuCode,
                    modules[componentPath]()
                );
            } else {
                console.error(`Component not found: ${componentPath}`);
                component = {
                    template: `<div>Component not found: ${item.node.menuCode}</div>`
                };
            }
            permissions = [...permissions, item.node.menuUrl];
        }
        // 存储按钮权限
        if (item.node.buttonList && item.node.buttonList.length) {
            console.log('按钮权限');
            const list = item.node.buttonList.map((item) => item.btnCode);
            permissions = [...permissions, ...list];
        }
        const currentRouter = {
            path: '',
            // 路由名称，建议唯一
            name: item.node.menuCode,
            // 该路由对应页面的 组件
            component,
            // meta: 页面标题, 菜单图标, 页面权限(供指令权限用，可去掉)
            meta: {
                title: item.node.menuName,
                menuGroup: item.node.menuGroup,
                isHide: +item.node.isVisible ? false : true,
                keepAlive: +item.node.isKeepAlive ? true : false,
                icon: item.node.menuIcon || undefined,
                isHasGroup: false
            }
        };
        // 有子菜单
        if (hasChildren) {
            currentRouter.path = `/${uuidv4()}`;
            // 子节点是否都隐藏
            const isHideArrow = item.subNodes.every((item) => item.node.isVisible === '0');
            currentRouter.meta.isHideArrow = isHideArrow;
            // 子节点是否有分组
            const isHasGroup = item.subNodes.some((item) => item.node.menuGroup);
            currentRouter.meta.isHasGroup = isHasGroup;
            // 重定向，默认都是第一个子节点路径
            currentRouter.redirect = item.subNodes[0].node.menuUrl.replace('//', '/');
        } else if (item.node.menuUrl) {
            // 页面
            currentRouter.path = item.node.menuUrl;
            currentRouter.path = currentRouter.path.replace('//', '/');
        }
        // 是否有子菜单，并递归处理
        if (hasChildren) {
            // Recursion
            currentRouter.children = generator(item.subNodes);
        }
        return currentRouter;
    });
};